﻿using AutoScaleHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;
using Newtonsoft.Json;
using System.IO;
using System.Net;

namespace Tool
{
    public partial class ReqTool : Form
    {
        AutoScale autoScale = new AutoScale();

        //请求方式
        private readonly List<string> reqMethodList = new List<string>() { "POST", "GET" };

        public ReqTool()
        {
           
            InitializeComponent();
            autoScale.SetContainer(this);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void ReqTool_Load(object sender, EventArgs e)
        {
            this.comboBox1.Items.Clear();
            foreach (var item in reqMethodList)
            {
                this.comboBox1.Items.Add(item);
            }
            this.comboBox1.SelectedItem = "POST";
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            this.SuspendLayout();
            autoScale.UpdateControlsLayout();
            this.ResumeLayout();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //发送请求
        private void SendButton_Click(object sender, EventArgs e)
        {
            string url = this.UrlTextBox.Text;
            string strJsonReq = this.ReqTextBox.Text;
            string selectedReqType = this.comboBox1.SelectedItem.ToString();
            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("请求地址不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(strJsonReq))
            {
                MessageBox.Show("请求参数不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(selectedReqType))
            {
                MessageBox.Show("请求类型不能为空!");
                return;
            }
            if (selectedReqType.Equals("GET"))
            {
                MessageBox.Show("当前不支持GET方式!");
                return;
            }

            // 使用 BackgroundWorker 来执行耗时的后台操作
            string retStr = "";
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, e1) =>
            {
                // 在这里执行耗时的操作
                // 注意：该代码不在 UI 线程上运行
                retStr = SendPost(url, strJsonReq);
                if (string.IsNullOrEmpty(retStr))
                {
                    MessageBox.Show("调用失败!");
                    return;
                }
            };
            worker.RunWorkerCompleted += (s, e2) =>
            {
                // 此事件处理器在 UI 线程上执行
                if (e2.Error != null)
                {
                    // 处理在 DoWork 事件中发生的任何异常
                }
                else
                {
                    // 安全地更新 UI 线程上的控件
                    this.RetTextBox.Text = retStr;
                }
            };
            // 开始异步操作
            worker.RunWorkerAsync();
        }


        private string SendPost(string url ,string strJsonReq) 
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";//请求方式
/*            req.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/537.36 (KHTML,like GeCKO) Chrome/45.0.2454.85 Safari/537.36 115Broswer/6.0.3";
            req.Headers["Connection"] = "keep-alive";
            req.Headers["Transfer-Encoding"] = "chunked";*/
            req.ContentType = "application/json; charset=UTF-8";//添加请求头
            string mapStr = JsonConvert.SerializeObject(strJsonReq);//转换为json
            byte[] data = Encoding.UTF8.GetBytes(mapStr);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();  //发送请求
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);//解析
            string strRet = streamReader.ReadToEnd();//请求返回值
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(strRet);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,//缩进字符数
                    IndentChar = ' '//缩进字符
                };
                serializer.Serialize(jsonWriter, obj);
                
                return textWriter.ToString();
            }
            return "";
        }




    }
}
